package cn.control;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.entity.goods;
import cn.DB.DBProcess;

public class Ctrl extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public Ctrl() {
		super();
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		 request.setCharacterEncoding("utf-8");

		String forward = "list.jsp";
		String action = request.getParameter("action");
		DBProcess db = new DBProcess();
		try {
			if (action == null || "list".equals(action)) {
				ArrayList<goods> goodslist = db.getgoodsList();
				request.setAttribute("goodslist", goodslist);
			} else if ("edit".equals(action)) {
				String goodid = request.getParameter("goodid");
				goods goo = db.getgoodsById(goodid);
				request.setAttribute("goo", goo);
				forward = "edit.jsp";

			} else if ("save".equals(action)) {
				String oldId = request.getParameter("oldId");
				goods goo = new goods();

				goo.setgoodid(request.getParameter("goodid"));
				goo.setgoodname(request.getParameter("goodname"));

				// 变量类型转换
				String goodprice1 = request.getParameter("goodprice");
				float goodprice = Float.parseFloat(goodprice1);
				goo.setgoodprice(goodprice);

				goo.setgoodproperty(request.getParameter("goodproperty"));

				// 变量类型转换
				String goodqty1 = request.getParameter("goodqty");
				// System.out.println("符合看电视剧发挥空间"+goodqty1);
				int goodqty = Integer.parseInt(goodqty1);
				goo.setgoodqty(goodqty);

				boolean add = "".equals(oldId);

				db.savegoods(goo, add, oldId);
				response.sendRedirect("Ctrl");

				return;

			}

			else if ("delete".equals(action)) {
				String goodid = request.getParameter("goodid");
				db.deleteById(goodid);
				response.sendRedirect("Ctrl");
				return;

			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new java.lang.NumberFormatException("bage hdskajfh");
		}
		// 重定向
		request.getRequestDispatcher(forward).forward(request, response);
	}

}
